<template>
	<view class="page-container">
		<uni-section title="新增用户" type="line">
			<view class="example">
				<!-- The 'model' prop should be bound to 'valiFormData' -->
				<uni-forms v-if="dataLoaded" ref="valiForm" :rules="rules" :model="valiFormData" label-position="top">

					<uni-forms-item label-width="150rpx" label="手机号" required name="mobile">
						<uni-easyinput v-model="valiFormData.mobile" placeholder="请输入手机号" />
					</uni-forms-item>

					<uni-forms-item label-width="150rpx" label="姓名" required name="username">
						<uni-easyinput v-model="valiFormData.username" placeholder="请输入姓名" />
					</uni-forms-item>

					<uni-forms-item label-width="150rpx" label="短码" name="short">
						<uni-easyinput v-model="valiFormData.short" placeholder="请输入短码" />
					</uni-forms-item>

					<uni-forms-item label-width="150rpx" label="座机" name="telphone">
						<uni-easyinput v-model="valiFormData.telphone" placeholder="请输入座机" />
					</uni-forms-item>

					<!-- Changed name from "d_ids" to "d_id" to match the updated data structure -->
					<uni-forms-item label-width="150rpx" label="部门" required name="d_id">
						<uni-data-select placeholder="请选择" :localdata="d_ids" v-model="dvalue" @change="d_change" />
					</uni-forms-item>

					<!-- Changed name from "j_ids" to "j_id" to match the updated data structure -->
					<uni-forms-item label-width="150rpx" label="职务" required name="j_id">
						<uni-data-select placeholder="请选择" :localdata="j_ids" v-model="jvalue" @change="j_change" />
					</uni-forms-item>

					<uni-forms-item label-width="150rpx" label="备注" name="comment">
						<uni-easyinput type="textarea" v-model="valiFormData.comment" placeholder="请输入备注" />
					</uni-forms-item>

				</uni-forms>

				<button class="submit-btn" @click="submit('valiForm')">提交</button>
			</view>
		</uni-section>
	</view>
</template>

<script>
	import whtMd5 from '@/uni_modules/wht-md5/js_sdk/wht-md5.js'

	export default {
		data() {
			return {
				dataLoaded: false, // 新增加载状态
				dvalue: null,
				jvalue: null,
				d_ids: [],
				j_ids: [],
				valiFormData: {
					mobile: '',
					username: '',
					comment: '',
					short: '',
					telphone: '',
					// Changed d_ids and j_ids to singular and initialized to null
					d_ids: null,
					j_ids: null,
					status: 0,
					password: this.encrypt('111111'),
					role: {
						value: 0,
						text: '普通用户'
					},
					register_date: ''
				},
				rules: {
					mobile: {
						rules: [{
								required: true,
								errorMessage: '请输入手机号'
							},
							{
								validateFunction: function(rule, value, data, callback) {
									const mobileStr = String(value);
									const pattern = /^1[3-9]\d{9}$/;
									if (value && !pattern.test(mobileStr)) {
										callback(new Error('手机号格式不正确'));
									}
									return true;
								}
							}
						]
					},
					username: {
						rules: [{
							required: true,
							errorMessage: '姓名不能为空'
						}, {
							minLength: 2,
							errorMessage: '姓名必须2个字以上'
						}]
					},
					// Changed rule to target d_id
					d_ids: {
						rules: [{
							required: true,
							errorMessage: '请选择一个部门'
						}]
					},
					// Changed rule to target j_id
					j_ids: {
						rules: [{
							required: true,
							errorMessage: '请选择一个职务'
						}]
					}
				}
			}
		},
		// mounted() {
		// 	this.getdep()
		// 	this.getjob()
		// },
		async mounted() {
		    await Promise.all([this.getdep(), this.getjob()]);
		    this.dataLoaded = true; // 数据就绪后再渲染
		  },
		methods: {
			encrypt(pwd) {
				return whtMd5(pwd)
			},
			async getdep() {
				const obj = uniCloud.importObject('basedata')
				try {
					const res = await obj.getdepselect({
						data: {},
						field: {
							name: true,
							sort: true
						}
					})
					if (res.code === 0 && Array.isArray(res.data)) {
						this.d_ids = res.data.map(item => ({
							value: item._id,
							text: item.name,
							sort: item.sort
						}))
					} else {
						this.d_ids = []
						uni.showToast({
							title: res.message || '部门数据异常',
							icon: 'none'
						})
					}
				} catch (e) {
					this.d_ids = []
					uni.showToast({
						title: '获取部门出错',
						icon: 'none'
					})
				}
			},
			async getjob() {
				const obj = uniCloud.importObject('basedata')
				try {
					const res = await obj.getjobselect({
						data: {},
						field: {
							name: true,
							sort: true
						}
					})
					if (res.code === 0 && Array.isArray(res.data)) {
						this.j_ids = res.data.map(item => ({
							value: item._id,
							text: item.name,
							sort: item.sort
						}))
					} else {
						this.j_ids = []
						uni.showToast({
							title: res.message || '职务数据异常',
							icon: 'none'
						})
					}
				} catch (e) {
					this.j_ids = []
					uni.showToast({
						title: '获取职务出错',
						icon: 'none'
					})
				}

			},
			d_change(e) {
				console.log(e,'1111111')
				// The 'e' parameter is the selected value, not the full object
				if (e !== null) {
					this.dvalue = e.value
					// Assign the selected ID to valiFormData.d_id
					this.valiFormData.d_ids = e
				}
			},
			j_change(e) {
				// The 'e' parameter is the selected value, not the full object
				if (e !== null) {
					this.jvalue = e.value
					// Assign the selected ID to valiFormData.j_id
					this.valiFormData.j_ids = e
				}
			},
			submit(ref) {
				this.$refs[ref].validate().then(res => {
					// The form data is already correctly structured in this.valiFormData
					const formData = {
						...this.valiFormData,
						mobile: this.valiFormData.mobile ? Number(this.valiFormData.mobile) : undefined,
						short: this.valiFormData.short ? Number(this.valiFormData.short) : undefined,
						telphone: this.valiFormData.telphone ? Number(this.valiFormData.telphone) : undefined,
						register_date: uni.$dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')
					}

					// Corrected the uniCloud object import and usage
					const obj = uniCloud.importObject('users')
					obj.register(formData).then(res => {
						if (res.code === 0) {
							uni.showToast({
								title: res.message,
								icon: 'success'
							})
							setTimeout(() => {
								uni.navigateBack()
							}, 1000)
						} else {
							uni.showToast({
								title: res.message,
								icon: 'none'
							})
						}
					})
				}).catch(err => {
					// It's good practice to log validation errors for debugging
					console.error('表单验证失败:', err)
				})
			}
		}
	}
</script>

<style lang="scss">
	// 页面整体背景
	page {
		background: linear-gradient(135deg, #e6f7ff, #f0f8ff);
		min-height: 100vh;
		box-sizing: border-box;
	}

	.page-container {
		padding: 20rpx;
	}

	// 卡片容器
	.uni-section {
		margin: 0;
		border-radius: 24rpx;
		overflow: hidden;
		box-shadow: 0 8rpx 24rpx rgba(0, 105, 204, 0.1);
		background: #fff;
	}

	// 卡片标题
	::v-deep .uni-section__header-title {
		font-size: 36rpx !important;
		font-weight: 600 !important;
		color: #0069cc !important;
	}

	::v-deep .uni-section__header {
		padding: 28rpx 30rpx !important;
		background: #f0f8ff !important;
		border-bottom: 1px solid #e0f0ff;
	}

	.example {
		padding: 40rpx 30rpx;
		background-color: #fff;
	}

	// 表单项
	.uni-forms-item {
		margin-bottom: 40rpx;

		// 表单标签
		::v-deep .uni-forms-item__label {
			font-size: 30rpx !important;
			font-weight: 500;
			color: #0069cc !important;
			// margin-bottom: 16rpx;
		}

		// 输入框和选择器样式
		::v-deep .uni-easyinput__content,
		::v-deep .uni-select {
			border: 1px solid #d1e9ff !important;
			border-radius: 12rpx !important;
			background: #f9fcff !important;
			transition: all 0.3s;
			// height: 80rpx;
			padding: 0 24rpx !important;
			// line-height: 80rpx;

			&:focus-within,
			&.uni-select--open {
				border-color: #0069cc !important;
				box-shadow: 0 0 0 2px rgba(0, 105, 204, 0.2);
			}

			.uni-input-input,
			.uni-select__input-text {
				font-size: 28rpx;
				color: #333;
			}

			.uni-input-placeholder,
			.uni-select__input-placeholder {
				color: #999 !important;
			}
		}
	}

	// 提交按钮
	.submit-btn {
		background: linear-gradient(135deg, #0081ff, #0069cc);
		border: none;
		border-radius: 50rpx;
		height: 88rpx;
		font-size: 32rpx;
		font-weight: 500;
		color: #fff;
		margin-top: 40rpx;
		box-shadow: 0 8rpx 24rpx rgba(0, 105, 204, 0.3);
		transition: all 0.3s;

		// 移除默认按钮边框
		&::after {
			border: none;
		}

		&:active {
			transform: translateY(4rpx);
			box-shadow: 0 4rpx 12rpx rgba(0, 105, 204, 0.3);
		}
	}
</style>